package com.carassistant.beta.phone.adapter;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.carassistant.beta.R;
import com.carassistant.beta.common.BitmapCache;

public class RecentAdapter extends BaseAdapter{
	private ArrayList<ContentValues> calllogs;
	private Context mContext;
	private Drawable[] types; 
	
	private RelativeLayout.LayoutParams params;
	private int height; 
	
	public RecentAdapter(Activity mContext, ArrayList<ContentValues> calllogs){
		this.calllogs = calllogs;
		this.mContext = mContext;
		types = new Drawable[3];
		types[0] = mContext.getResources().getDrawable(android.R.drawable.sym_call_incoming);;
		types[1] = mContext.getResources().getDrawable(android.R.drawable.sym_call_outgoing);
		types[2] = mContext.getResources().getDrawable(android.R.drawable.sym_call_missed);
		
		height = getScreenHeight(mContext, 5f); 
		params = new RelativeLayout.LayoutParams(height, height);
		params.setMargins(5, 10, 5, 10);
	}
	
	private int getScreenHeight(Activity activity, float divide){
		DisplayMetrics metrics = new DisplayMetrics();  
		activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); 
		int height = (metrics.widthPixels  < metrics.heightPixels) ? metrics.widthPixels : metrics.heightPixels;
		height = (int)(height / divide); 
		return height;
	}
	
	@Override
	public int getCount() {
		if (calllogs == null) {
			return 0;
		}
		return calllogs.size();
	}

	public void notifyData(ArrayList<ContentValues> list){
		this.calllogs = list;
		notifyDataSetChanged();
	}
	
	@Override
	public Object getItem(int position) { 
		return calllogs.get(position).getAsString(CallLog.Calls.NUMBER);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) { 
		ViewHolder holder;
		if (convertView == null) {
			convertView = LayoutInflater.from(mContext).inflate(R.layout.phone_contact_call_log_item, null); 
			holder = new ViewHolder();
			holder.image = (ImageView) convertView
					.findViewById(R.id.image_view);
			holder.type = (ImageView) convertView.findViewById(R.id.type);
			holder.name = (TextView) convertView.findViewById(R.id.name);
			holder.date = (TextView) convertView.findViewById(R.id.date);
			
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		String name = calllogs.get(position).getAsString(CallLog.Calls.CACHED_NAME);
		if (name == null || name.equals("")) {
			holder.name.setText(calllogs.get(position).getAsString(CallLog.Calls.NUMBER));
		} else {
			holder.name.setText(name);
		}
		
		
		if (name == null || name.equals("")) {
			holder.image.setImageBitmap(BitmapCache.getInstance().getBitmap2(mContext.getResources(), R.drawable.default_contact_icon));
		}else{
			Bitmap icon = getContactIcon(name);
			if (icon != null) {
				holder.image.setImageBitmap(icon); 
			} else{
				holder.image.setImageBitmap(BitmapCache.getInstance().getBitmap2(mContext.getResources(), R.drawable.default_contact_icon));
			}
		}
		
		SimpleDateFormat sfd = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
		Date date = new Date(Long.parseLong(calllogs.get(position).getAsString(CallLog.Calls.DATE)));
		String time = sfd.format(date);//格式化的效果:例如2010-01-08 09:10:11
		holder.date.setText(time);
		
		int typeID = calllogs.get(position).getAsInteger(CallLog.Calls.TYPE) - 1;
		if (typeID < 0) {
			typeID = 0;
		}
		
		if (typeID > 2) {
			typeID = 2;
		}
		holder.type.setImageDrawable(types[typeID]);  
		return convertView;
	}
	
	private class ViewHolder {
		ImageView image;
		ImageView type;
		TextView name;
		TextView date;
	}

	/**
	 * 根据联系人名字获取联系人头像
	 * @param name
	 * @return Bitmap
	 * */
	private Bitmap getContactIcon(String name){
		 Bitmap bitmap = null;
		 
		 Uri uri = Uri.parse("content://com.android.contacts/data/phones/filter/"+formatName(name));
		 Cursor cursor2=mContext.getContentResolver().query(uri, new String[]{"photo_id"}, null, null, null);
		 if(cursor2.moveToFirst()){
		    String phot_IDo=cursor2.getString(0);
		    if(phot_IDo!=null){
		       Cursor cursor3=mContext.getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[]{"data15"}, "ContactsContract.Data._ID="+phot_IDo, null, null);
		       if(cursor3.moveToFirst()){
			     byte [] photoicon=cursor3.getBlob(0);
			     ByteArrayInputStream inputStream=new ByteArrayInputStream(photoicon);
			     bitmap = BitmapFactory.decodeStream(inputStream);
		       }
		    }
		 }
	    	
		 return bitmap;
	  }
	
	private String formatName(String name){
		String str = name;
		
		if(str.indexOf("/") >= 0){
			str = str.replace("/", "");
		}
		
		return str;
	}
}
